﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using baseSet.importExport;
using dhDataAcess.produceDAL;
using dhSystemBLL.produceBLL;
using dhSystemBLL.basicData;
using dhDataAcess.dataAcess.purchaseTableAdapters;
using dhDataAcess.dataAcess;
using baseSet;
using dhDataAcess.produceLinq;
using dhDataAcess.baseBLL;
using dhSystemBLL.orderData;
using dhDataAcess.dataAcess.produceDataSetTableAdapters;
using dhsystem.Main;
using System.Data.SqlClient;

namespace dhsystem.produceForm.picking
{
    public partial class FrmproductblMasterAdd : Form
    {
        produceDataSet.machineTableDataTable machineTable = new produceDataSet.machineTableDataTable();
        machineTableBLL machine = new machineTableBLL();
        productblDetailModel productblDetailRow = new productblDetailModel();
        productblBLL productbl = new productblBLL();
        productblMasterModel productblMasterRow = new productblMasterModel();
        purchase.productblDetailDataTable productblTable = new purchase.productblDetailDataTable();
       
        scrlBLL scrl = new scrlBLL();
        BindingSource b2;
        string state;
        string pname;
        string unit;
        string orderDetailNo;
        string qty;
        string qtyM;
        string billNo;
        pbomDetailBLL pbomDetail = new pbomDetailBLL();

        public FrmproductblMasterAdd(BindingSource b1, string _state, string _pname, string _unit, string _orderDetailNo,string _qty,string _qtyM,string _billNo)
        {
            InitializeComponent();
            state = _state;
            b2 = b1;
            pname =_pname;
            unit = _unit;
            qty = _qty;
            qtyM = _qtyM;
            orderDetailNo = _orderDetailNo;
            billNo = _billNo;
        }
        //选择产品名称
        private void buttselectpname_Click(object sender, EventArgs e)
        {
            string field;
            field = "pname";
            Frmgetorder productselect = new Frmgetorder( field);
            DialogResult result = productselect.ShowDialog();
            if (result == DialogResult.Yes)
            {
                textpname.Text = productselect.pname;
            }
        }
        //打开窗口时绑定数据
        private void FrmproductblMasterAdd_Load(object sender, EventArgs e)
        {
            if (state == "复制")
            {
                textbillNo.Text = "B" + GlobalInfo.Date + "-" + basicSql.getOrderSerail("备料单号");
                textpname.DataBindings.Add("text", b2, "pname");
                textjiqiNo.DataBindings.Add("text", b2, "jiqiNo");
                texttuoshu.DataBindings.Add("text", b2, "tuoshu");
               
                textqtykg.DataBindings.Add("text", b2, "qtykg");
                //dateTimeproductDate.DataBindings.Add("value", b2, "productDate");
                //dateTimeendDate.DataBindings.Add("value", b2, "endDate");
                textunit.DataBindings.Add("text", b2, "unit");
                textmark.DataBindings.Add("text", b2, "mark");
                textqty.DataBindings.Add("text", b2, "qty");
                bindingSourceproductblDetail.DataSource = productbl.getsproductblDetailAllBybillNo(billNo );
                dGridDetail.DataSource = bindingSourceproductblDetail;
            }

            if (state == "新增")
            {
                textpdweight.Text = basicSql.getgrwightbyproductList(pname  ); 
                textunit.Text = unit;
                textpname.Text = pname;
                textbillNo.Text = "B" + GlobalInfo.Date + "-" + basicSql.getOrderSerail("备料单号");
                textqty.Text = qtyM ;
                //bindingSourceproductblDetail.DataSource = productbl.getsproductblDetailAllBybillNo(textbillNo.Text);
                //dGridDetail.DataSource = bindingSourceproductblDetail;
                //textendopen.Text = basicSql.getendopenbypbomMark(pname);
              
            }
            if (state == "编辑")
            {
                textpname.DataBindings.Add("text", b2, "pname");
                textjiqiNo.DataBindings.Add("text", b2, "jiqiNo");
                textbillNo.DataBindings.Add("text", b2, "billNo");
                texttuoshu.DataBindings.Add("text", b2, "tuoshu");
                textqty.DataBindings.Add("text", b2, "qty");
                textqtykg.DataBindings.Add("text", b2, "qtykg");
                //dateTimeproductDate.DataBindings.Add("value", b2, "productDate");
                //dateTimeendDate.DataBindings.Add("value", b2, "endDate");
                textunit.DataBindings.Add("text", b2, "unit");
                textmark.DataBindings.Add("text", b2, "mark");
                bindingSourceproductblDetail.DataSource = productbl.getsproductblDetailAllBybillNo (textbillNo.Text);
                dGridDetail.DataSource = bindingSourceproductblDetail;
            }
            DcolumnSet.colSet(moduleInfo.productblDetail , dGridDetail);
           // dGridDetail.AllowUserToAddRows = false;

            dGridDetail.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dGridDetail.CellMouseUp += new DataGridViewCellMouseEventHandler(dGridDetail_CellMouseUp);
            this.dGridDetail.EditMode = DataGridViewEditMode.EditOnEnter ;
            textzzproduction.Text = basicSql.getproductionKfbypbomMark(textpname.Text );
            textendopen.Text = basicSql.getendopenbypbomMark(textpname.Text);
        }
        //状态栏退出按钮
        private void toolExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //菜单栏保存按钮
        private void toolSave_Click(object sender, EventArgs e)
        {

            decimal qtyM = 1;

            if (textunit.Text == "GR")
            {
                qtyM = Convert.ToDecimal(textqty.Text) * Convert.ToDecimal(basicSql.getUnitrateM(textunit.Text));

            }
            if (textunit.Text == "M")
            {
                qtyM = Convert.ToDecimal(textqty.Text);

            }
            if (textunit.Text == "Y")
            {
                qtyM = Convert.ToDecimal(textqty.Text) * Convert.ToDecimal(basicSql.getUnitrateM(textunit.Text));

            }
            //if (texttuoshu.Text == "")
            //{
            //    MessageBox.Show("请输入头数");
            //}

            //else
            //{
                try
                {
                    SendKeys.Send("{Tab}"); 
                    DialogResult result = MessageBox.Show("是否保存信息！", "提示信息", MessageBoxButtons.YesNo);

                    if (result == DialogResult.Yes)
                    {
                        purchase.productblDetailDataTable ptable = (purchase.productblDetailDataTable)bindingSourceproductblDetail.DataSource;
                        purchase.productblDetailDataTable ptableI = new purchase.productblDetailDataTable();
                        foreach (purchase.productblDetailRow Row in ptable)
                        {
                            purchase.productblDetailRow RowI = ptableI.NewproductblDetailRow ();
                            if (Row.matNum == "0")
                            {
                                continue;
                            }
                            else { RowI.matNum = Row.matNum; }
                            RowI.stockqty = Convert.ToDecimal(basicSql.getstockqtybymaterialList(Row.matNum));
                            RowI.stockKg = Math.Round((Convert.ToDecimal(qtyM) * Convert.ToDecimal(Row.pweight)) / 100, 2);
                            RowI.matName = basicSql.getmatNamebymaterialList(Row.matNum);

                            if (!Row.IswbNull ())
                            {
                                RowI.wb = Row.wb;
                            }
                            else { RowI.wb = ""; }
                          
                                RowI.pweight = Row.pweight;
                            
                           
                        
                            if (!Row.IspzNull ())
                            {
                                RowI.pz = Row.pz;
                            }
                            else { RowI.pz = ""; }
                            if (!Row.IstsNull ())
                            {
                                RowI.ts  = Row.ts;
                            }
                            else { RowI.ts = 0; }
                            if (!Row.IsoldgsNull ())
                            {
                                RowI.oldgs = Row.oldgs;
                            }
                            else { RowI.oldgs = 0; }
                            if (!Row.IsoldtsNull ())
                            {
                                RowI.oldts = Row.oldts;
                            }
                            else { RowI.oldts = 0; }
                            if (!Row.IsgsNull ())
                            {
                                RowI.gs = Row.gs;
                            }
                            else { RowI.gs = 0; }
                            ptableI.AddproductblDetailRow(RowI);
                        }
                        productblMasterRow.billNo = textbillNo.Text;
                        productblMasterRow.billStatus = "新建";
                        productblMasterRow.createDate = DateTime.Now;
                        productblMasterRow.createUser = GlobalInfo.UserName;
                        productblMasterRow.endDate = DateTime.Now;
                        productblMasterRow.jiqiNo = textjiqiNo.Text;
                        productblMasterRow.pname = textpname.Text;
                        productblMasterRow.productDate = DateTime.Now;
                        productblMasterRow.qty =Convert .ToDecimal(textqty.Text);
                      
                        productblMasterRow.qtykg =Convert .ToDecimal ( textqtykg.Text);
                        if (texttuoshu.Text == "")
                        {
                            productblMasterRow.tuoshu = 0;
                        }

                        else
                        {
                            productblMasterRow.tuoshu = Convert.ToInt32(texttuoshu.Text);
                        }
                        productblMasterRow.unit = textunit.Text;
                        productblMasterRow.mark = textmark.Text;
                        if (state == "新增")
                        {
                            bindingSourceproductblDetail.AddNew();
                        }
                       // bindingSourceproductblDetail.AddNew();
                        
                        productbl.productblInsert(productblMasterRow, ptableI, state, GlobalInfo.UserName, textbillNo .Text , GlobalInfo.Date);
                        ptable.AcceptChanges();
                        bindingSourceproductblMaster.DataSource = productbl.getproductblMasterAll();

                        basicSql.getdetailStatusUpdatebypname(textpname.Text, "已处理");

                        MessageBox.Show("保存成功");
                    }
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            //}
        }
        //菜单栏删除按钮
        private void toolDel_Click(object sender, EventArgs e)
        {
            try
            {
           
                    string billoNo = dGridDetail.Rows[dGridDetail.CurrentRow.Index].Cells[1].Value.ToString();
                    DialogResult result = MessageBox.Show("是否删除明细！", "提示信息", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        dGridDetail.Rows.Remove(dGridDetail.CurrentRow);
                    }
                }
           
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

        }

        private void dGridDetail_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string field;
            field = "matNum";
            int colIndex = dGridDetail.Columns["matNum"].Index;
            int colIndexmark = dGridDetail.Columns["mark"].Index;
            if (colIndex == e.ColumnIndex)
            {
                Frmprodutselect select = new Frmprodutselect(moduleInfo.materialList, field);
                DialogResult result = select.ShowDialog();
                if (result == DialogResult.Yes)
                {

                    dGridDetail.CurrentCell.Value = select.pname;
                }
            }
            if (colIndexmark == e.ColumnIndex)
            {
                Frmmark mark = new Frmmark();
                DialogResult result = mark.ShowDialog();
                if (result == DialogResult.Yes)
                {

                    dGridDetail.CurrentCell.Value = mark.mark;
                }
            }
        }

        private void dGridDetail_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (e.ColumnIndex == dGridDetail.Columns["stockLength"].Index)
            {
                MessageBox.Show(e.Exception.Message.ToString());
            }
            MessageBox.Show(e.Exception.Message.ToString());
        }
        /// <summary>  
        /// 设置编辑状态下按回车键，跳到指定单元格.  
        /// </summary>  
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            string field;
            field = "matNum";
            if (keyData == Keys.Enter)    //监听回车事件   
            {
                if (this.dGridDetail.IsCurrentCellInEditMode)   //如果当前单元格处于编辑模式   
                {

                    if (this.dGridDetail.CurrentCell.ColumnIndex == 2)
                    {
                        Frmprodutselect select = new Frmprodutselect(moduleInfo.materialList, field);
                        DialogResult result = select.ShowDialog();
                        if (result == DialogResult.Yes)
                        {
            

                            dGridDetail.CurrentRow.Cells["matNum"].Value = select.pname;
   
                        }
                    }

                    if (this.dGridDetail.CurrentCell.ColumnIndex != 12)
                    {
                        SendKeys.Send("{Up}");
                        SendKeys.Send("{Tab}");
  
                    }

                    else
                    {
                        SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}");
                        SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}");
                    }
                }
                else
                {
                    SendKeys.Send("{Up}");
                    SendKeys.Send("{Tab}");
                    //SendKeys.Send("{Tab}");
                    //SendKeys.Send("{Tab}");
                }


            }

            if (keyData == Keys.F3)
            {
                int cRowIndex = dGridDetail.CurrentCell.RowIndex;
                int cCellIndex = dGridDetail.CurrentCell.ColumnIndex;
                dGridDetail.CurrentCell.Value = dGridDetail.Rows[cRowIndex - 1].Cells[cCellIndex].Value;
                if (cCellIndex == 2 || cCellIndex == 0)
                {
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex + 3];
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex];
                }
                else
                {
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex - 1];
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex];
                }
            }

            //继续原来base.ProcessCmdKey中的处理   
            return base.ProcessCmdKey(ref msg, keyData);

        }
        //产品名称选择按钮
        private void button1_Click(object sender, EventArgs e)
        {
            string field;
            field = "pname";
            Frmprodutselect productselect = new Frmprodutselect(moduleInfo.productList, field);
            DialogResult result = productselect.ShowDialog();
            if (result == DialogResult.Yes)
            {
                textpname.Text = productselect.pname;
            }
        }

        private void dGridDetail_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

            if (dGridDetail.Rows.Count > 0 && e.RowIndex >= 0)
            {
                DataGridViewRow row = dGridDetail.Rows[e.RowIndex];
                if (row.Cells[e.ColumnIndex].OwningColumn.Name == "ts")
                {
                    try
                    {
                        row.Cells["stockKg"].Value = Math.Round((Convert.ToDecimal(textqty.Text ) * Convert.ToDecimal(row.Cells["pweight"].Value)) / 100, 2);
 


                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            }
        }

        private void textpname_TextChanged(object sender, EventArgs e)
        {
            try
            {

                orderDataSet.pbomDetailDataTable pbomDetailTable = pbomDetail.getpbomDetailbypanmeAll(pname);
                
                foreach (orderDataSet.pbomDetailRow pbomRow in pbomDetailTable)
                {
                    purchase.productblDetailRow productblRow = productblTable.NewproductblDetailRow();
                    if (pbomRow.matNum == "0")
                    {
                        continue  ;
                    }
                    else { productblRow.matNum = pbomRow.matNum; }
                    productblRow.stockqty =Convert .ToDecimal ( basicSql.getstockqtybymaterialList ( productblRow.matNum));
                    productblRow.stockKg = Math.Round((Convert.ToDecimal(qtyM) * Convert.ToDecimal(pbomRow .pweight)) / 100, 2); 
                    //if (!pbomRow.IsmatNameNull())
                    //{
                    //    productblRow.matName = pbomRow.matName;
                    //}
                    //else { productblRow.matName = ""; }
                      productblRow.matName = basicSql.getmatNamebymaterialList(productblRow.matNum);
                      if (!pbomRow.IswbNull ())
                      {
                          productblRow.wb  = pbomRow.wb ;
                      }
                      else { productblRow.wb = ""; }
                    if (!pbomRow.IspweightNull ())
                    {
                        productblRow.pweight  = pbomRow.pweight ;
                    }
                    else { productblRow.pweight  = 0; }
                    if (!pbomRow.IspzNull())
                    {
                        productblRow.pz = pbomRow.pz;
                    }
                    else { productblRow.pz = ""; }
                    if (!pbomRow.IstsNull())
                    {
                        productblRow.oldts  = pbomRow.ts;
                    }
                    else { productblRow.oldts = 0; }
                    productblTable.AddproductblDetailRow(productblRow);
                }
                bindingSourceproductblDetail.DataSource = productblTable;
                dGridDetail.DataSource = bindingSourceproductblDetail;
                //SqlDataReader dr = basicSql.getmachineNobymachineTable(pname);
                //foreach (string a in dr )
                //textjiqiNo.Text = basicSql.getmachineNobymachineTable(pname) ;
                machineTable = machine.getmachineTableAllBypname(pname);
              //  produceDataSet .machineTableRow machineRow=new produceDataSet.machineTableRow ();
                foreach (produceDataSet.machineTableRow machineRow in machineTable)
                {
                    if (machineTable.Count > 1)
                    {
                        textjiqiNo.Text = textjiqiNo.Text + machineRow.machineNo + " ";
                    }
                    //else if (machineTable.Count == machineTable.Count || machineTable.Count == 1)
                    //{
                    //    textjiqiNo.Text = textjiqiNo.Text + machineRow.machineNo;
                    //}
                    else
                    {
                        textjiqiNo.Text = textjiqiNo.Text + machineRow.machineNo;
                    }
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString());}
        }

        private void textqty_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (textunit .Text  == "GR")
                {
                    textqtykg.Text = (Convert.ToDecimal(textqty.Text) * Convert.ToDecimal(basicSql.getgrwightbyproductList(textpname.Text))).ToString("#0.00");

                }
                if (textunit.Text == "M")
                {
                    textqtykg.Text = (Convert.ToDecimal(textqty.Text) * Convert.ToDecimal(basicSql.getUnitrateL(textunit.Text)) * Convert.ToDecimal(basicSql.getgrwightbyproductList(textpname.Text))).ToString("#0.00");

                }
                if (textunit.Text == "Y")
                {
                    textqtykg.Text = (Convert.ToDecimal(textqty.Text) * Convert.ToDecimal(basicSql.getUnitrateL(textunit.Text)) * Convert.ToDecimal(basicSql.getgrwightbyproductList(textpname.Text))).ToString("#0.00");

                }
    
            }
          
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        private void dGridDetail_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            decimal  count = 0;
            for (int i = 0; i<dGridDetail.SelectedRows.Count; i++)
            {
                if (dGridDetail.SelectedRows[i].Cells[dGridDetail.CurrentCell.ColumnIndex].Value != null)
                {
                    try
                    {
                        count = count + decimal .Parse (dGridDetail.SelectedRows[i].Cells[dGridDetail.CurrentCell.ColumnIndex].Value.ToString());
                    }
                    catch (Exception)
                    {
                        continue;//非数字时,会报错,跳过
                    }
                }
            }
            if (count == 0)
            {
                this.textBox1.Text = "";
            }
            else
            {
                this.textBox1.Text = "求和=" + count.ToString();
            }
        }

        private void groupAdd_Enter(object sender, EventArgs e)
        {

        }

        private void dGridDetail_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void textqty_MouseLeave(object sender, EventArgs e)
        {
            //decimal qtyM = 1;

            //if (textunit.Text == "GR")
            //{
            //    qtyM = Convert.ToDecimal(textqty.Text) * Convert.ToDecimal(basicSql.getUnitrateM(textunit.Text));

            //}
            //if (textunit.Text == "M")
            //{
            //    qtyM = Convert.ToDecimal(textqty.Text);

            //}
            //if (textunit.Text == "Y")
            //{
            //    qtyM = Convert.ToDecimal(textqty.Text) * Convert.ToDecimal(basicSql.getUnitrateM(textunit.Text));

            //}
            //orderDataSet.pbomDetailDataTable pbomDetailTable = pbomDetail.getpbomDetailbypanmeAll(textpname.Text);

            //foreach (orderDataSet.pbomDetailRow pbomRow in pbomDetailTable)
            //{
                //orderDataSet.pbomDetailDataTable dt = (orderDataSet.pbomDetailDataTable)dGridDetail.DataSource;
                //dt.Rows.Clear();
                //dGridDetail.DataSource = dt;
                //dGridDetail.Rows.Clear();
            //    purchase.productblDetailRow productblRow = productblTable.NewproductblDetailRow();
            //    if (pbomRow.matNum == "0")
            //    {
            //        continue;
            //    }
            //    else { productblRow.matNum = pbomRow.matNum; }
            //    productblRow.matNum = pbomRow.matNum;
            //    productblRow.stockqty = Convert.ToDecimal(basicSql.getstockqtybymaterialList(productblRow.matNum));
            //    productblRow.stockKg = Math.Round((qtyM * Convert.ToDecimal(pbomRow.pweight)) / 100, 2);
            //    productblRow.matName = basicSql.getmatNamebymaterialList(productblRow.matNum);
            //    if (!pbomRow.IswbNull())
            //    {
            //        productblRow.wb = pbomRow.wb;
            //    }
            //    else { productblRow.wb = ""; }
            //    if (!pbomRow.IspweightNull())
            //    {
            //        productblRow.pweight = pbomRow.pweight;
            //    }
            //    else { productblRow.pweight = 0; }
            //    if (!pbomRow.IspzNull())
            //    {
            //        productblRow.pz = pbomRow.pz;
            //    }
            //    else { productblRow.pz = ""; }
            //    if (!pbomRow.IstsNull())
            //    {
            //        productblRow.oldts = pbomRow.ts;
            //    }
            //    else { productblRow.oldts = 0; }
            //    productblTable.AddproductblDetailRow(productblRow);
            //}
            //bindingSourceproductblDetail.DataSource = productblTable;
            //dGridDetail.DataSource = bindingSourceproductblDetail;
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void texttuoshu_TextChanged(object sender, EventArgs e)
        {
            //if (textzzproduction.Text != "")
            //{
            //    textdays.Text =Convert .ToString ((Convert .ToInt32  (textqty.Text )\ Convert.ToDecimal(textzzproduction.Text) * Convert.ToDecimal(texttuoshu.Text).ToString());
            //}
        }
    }
}
